import React, { useEffect, useState } from "react";
import {
  View,
  Swiper,
  SwiperItem,
  Text,
  Image,
  Picker,
} from "@tarojs/components";
import Taro, {
  useReachBottom,
  usePullDownRefresh,
  useRouter,
} from "@tarojs/taro";
import Advertisement from "@/components/Advertisement";
import GoodsItem from "@/components/GoodsItem";
import ListStatusInfo from "@/components/ListStatusInfo";
import { GoodsItemData } from "@/components/GoodsItem/data";
import SearchWrapper from "@/components/SearchWrapper";
import customNavigate from "@/common/hooks/useNavigate";
import useSearchAll from "@/common/hooks/useSearchAll";
import xialaChecked from "@/images/order_icon_xiala_select.png";
import xialaUnChecked from "@/images/order_icon_xiala_unselect.png";
import iconClose from "@/images/order_icon_pression_del.png";
import * as globalData from "@/src/globalData";

import * as api from "./api";
import "./index.scss";

interface IPagination {
  current: number;
  total?: number;
  pageSize?: number;
}

interface IsearchInfo {
  school?: number;
  major?: number;
  duration?: number;
  title?: string;
  city?: string;
}

const Index: React.FC<{}> = () => {
  const [data, setData] = useState<GoodsItemData[]>([]);
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState<number | null>(null);
  const [searchInfo, setSearchInfo] = useState<IsearchInfo>({});
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const allSchool = useSearchAll<{ id: number; name: string }>(
    "university.school.all",
    {}
  );
  const allMajor = useSearchAll<{ id: number; name: string }>(
    "university.major.all",
    {}
  );
  const allYear = useSearchAll<{ id: number; name: string }>(
    "university.major.duration",
    {}
  );

  const goGoodsDetail = (id) => {
    Taro.navigateTo({
      url: `/pages/goodsDetail/index?goods_id=${id}`,
    });
  };

  const getData = async (current_page = 1) => {
    try {
      setLoading(true);
      Taro.showNavigationBarLoading();
      const search_info: any = {};
      if (searchInfo.hasOwnProperty("school")) {
        search_info.school_id = allSchool[searchInfo.school as number].id;
      }

      if (searchInfo.hasOwnProperty("major")) {
        search_info.major_id = allMajor[searchInfo.major as number].id;
      }

      if (searchInfo.hasOwnProperty("duration")) {
        search_info.duration = allYear[searchInfo.duration as number].id;
      }

      if (router.params.category) {
        search_info.category = router.params.category;
      }

      if (router.params.title) {
        search_info.title = router.params.title;
      }

      if (searchInfo.title) {
        search_info.title = searchInfo.title;
      }

      if (Taro.getStorageSync("city")) {
        search_info.city = Taro.getStorageSync("city")[1];
      }

      const { result, status } = await api.production_goods_search({
        search_info: JSON.stringify(search_info),
        current_page: current_page,
      });
      if (status === "ok") {
        if (current_page === 1) {
          setCurrent(1);
          setData([].concat(result.data_list));
        } else {
          setData(data.concat(result.data_list));
        }

        setTotal(result.total);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideNavigationBarLoading();
      Taro.stopPullDownRefresh();
      setLoading(false);
    }
  };

  usePullDownRefresh(() => {
    getData(1);
  });

  useReachBottom(() => {
    if (data.length < total) {
      setCurrent(current + 1);
      getData(current + 1);
    }
  });

  useEffect(() => {
    getData(1);
  }, [searchInfo]);

  const onPickerChange = (e: any, key: keyof IsearchInfo) => {
    const currentSearchInfo: IsearchInfo = {
      ...searchInfo,
      [key]: Number(e.detail.value),
    };

    console.log("currentSearchInfo----->>", currentSearchInfo);
    setSearchInfo(currentSearchInfo);
  };

  const removeSearchInfoKey = (key: keyof IsearchInfo) => {
    const currentSearchInfo = {
      ...searchInfo,
    };

    delete currentSearchInfo[key];
    setSearchInfo(currentSearchInfo);
  };

  return (
    <View className="goods-page">
      <SearchWrapper
        onSearch={(value) => {
          globalData.setData("goodsTitle", value);
          setSearchInfo({ ...searchInfo, title: value });
        }}
        value={globalData.getData("goodsTitle")}
        onSelectRegion={(value) => {
          setSearchInfo({ ...searchInfo, city: value });
        }}
      />

      <Advertisement className="ad-space" label="index_mid" />

      <View className="option-search">
        <Picker
          mode="selector"
          range={allSchool}
          rangeKey="name"
          value={searchInfo.school || 0}
          onChange={(e) => onPickerChange(e, "school")}
          className="picker"
        >
          <View className="item">
            <View
              className={
                searchInfo.hasOwnProperty("school")
                  ? "text text__checked"
                  : "text"
              }
            >
              学校
            </View>
            <Image
              className="icon"
              src={
                searchInfo.hasOwnProperty("school")
                  ? xialaChecked
                  : xialaUnChecked
              }
            />
          </View>
        </Picker>

        <Picker
          mode="selector"
          range={allMajor}
          rangeKey="name"
          value={searchInfo.major || 0}
          onChange={(e) => onPickerChange(e, "major")}
          className="picker"
        >
          <View className="item">
            <View
              className={
                searchInfo.hasOwnProperty("major")
                  ? "text text__checked"
                  : "text"
              }
            >
              专业
            </View>
            <Image
              className="icon"
              src={
                searchInfo.hasOwnProperty("major")
                  ? xialaChecked
                  : xialaUnChecked
              }
            />
          </View>
        </Picker>

        <Picker
          mode="selector"
          range={allYear}
          rangeKey="name"
          value={searchInfo.duration || 0}
          onChange={(e) => onPickerChange(e, "duration")}
          className="picker"
        >
          <View className="item">
            <View
              className={
                searchInfo.hasOwnProperty("duration")
                  ? "text text__checked"
                  : "text"
              }
            >
              学年
            </View>
            <Image
              className="icon"
              src={
                searchInfo.hasOwnProperty("duration")
                  ? xialaChecked
                  : xialaUnChecked
              }
            />
          </View>
        </Picker>
      </View>

      <View className="selected">
        {searchInfo.hasOwnProperty("school") && (
          <View className="item" onClick={() => removeSearchInfoKey("school")}>
            <View className="text">
              {allSchool[searchInfo.school as number].name}
            </View>
            <Image className="close" src={iconClose} />
          </View>
        )}

        {searchInfo.hasOwnProperty("major") && (
          <View className="item" onClick={() => removeSearchInfoKey("major")}>
            <View className="text">
              {allMajor[searchInfo.major as number].name}
            </View>
            <Image className="close" src={iconClose} />
          </View>
        )}

        {searchInfo.hasOwnProperty("duration") && (
          <View
            className="item"
            onClick={() => removeSearchInfoKey("duration")}
          >
            <View className="text">
              {allYear[searchInfo.duration as number].name}
            </View>
            <Image className="close" src={iconClose} />
          </View>
        )}
      </View>

      {data.map((item) => (
        <View key={item.id} className="goods-item-wrap">
          <GoodsItem
            {...item}
            onClick={() => {
              goGoodsDetail(item.id);
            }}
          />
        </View>
      ))}
      <ListStatusInfo
        total={total}
        dataLength={data.length}
        loading={loading}
      />
    </View>
  );
};

export default Index;
